package com.common.app.base

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavCallback
import com.common.app.R
import com.common.app.core.RouterHub
import com.common.app.helper.RouterHelper
import com.common.app.helper.UserHelper
import com.common.app.utls.MD5Utils
import com.common.base.app.fragment.BaseVMFragment
import com.common.base.app.viewmodel.BaseViewModel
import com.common.base.security.Base64Utils
import com.common.base.utils.AppMarketUtils
import com.common.base.utils.ToastUtils
import com.common.base.widget.CustomDialog

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：
 * <p>
 * 修订历史：
 */

abstract class AppFragment<VB : ViewBinding, VM : BaseViewModel> : BaseVMFragment<VB, VM>() {

    /**
     * 两个按钮的自定义弹框
     */
    var mCerAurDialog: CustomDialog? = null

    /***
     * 打开应用市场
     * @param mContext
     * @param marketPackageName
     */
    open fun openMarket(mContext: Context, marketPackageName: String?) {
        try {
            AppMarketUtils.gotoMarket(requireActivity())
        } catch (anf: ActivityNotFoundException) {
            Log.e("MarketUtils", "要跳转的应用市场不存在!")
            openGoogleMarket(mContext, marketPackageName)
        } catch (e: Exception) {
            Log.e("MarketUtils", "其他错误：" + e.message)
        }
    }

    /***
     * 打开应用市场
     * @param mContext
     * @param marketPackageName
     */
    private fun openGoogleMarket(mContext: Context, marketPackageName: String?) {
        try {
            //谷歌商店
            val i = Intent(Intent.ACTION_VIEW)
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            i.data = Uri.parse("https://play.google.com/store/apps/details?id=$marketPackageName")
            startActivity(i)
        } catch (anf: ActivityNotFoundException) {
            Log.e("MarketUtils", "要跳转的应用市场不存在!")
        } catch (e: Exception) {
            Log.e("MarketUtils", "其他错误：" + e.message)
        }
    }


    /**
     * @param classUrl
     */
    open fun packageNameToApk(classUrl: String?, toApkJump: Boolean = false) {
        if (TextUtils.isEmpty(classUrl)) {

            RouterHelper.navigation(RouterHub.ROUTER_BE_OPENED_ACTIVITY)
            return
        }
        try {
            //包名跳转
            val intent = classUrl?.let { activity?.packageManager?.getLaunchIntentForPackage(it) }
            if (intent == null) {
                schemeToApk(classUrl, toApkJump)
                return
            }
            startActivity(intent)
        } catch (e: Exception) {
            Log.e("MarketUtils", "其他错误：" + e.message)
            schemeToApk(classUrl, toApkJump)
        }
    }

    /**
     * @param classUrl
     */
    open fun schemeToApk(classUrl: String?, toApkJump: Boolean,busType:Int =0) {
        if (TextUtils.isEmpty(classUrl)) {
            return
        }
        try {
            //深链跳转
            val action = Intent(Intent.ACTION_VIEW)
            action.data = Uri.parse(classUrl)
            startActivity(action)
        } catch (anf: ActivityNotFoundException) {
            Log.e("MarketUtils", "要跳转的应用市场不存在!")
            if (toApkJump) {
                val bundle = Bundle()
                bundle.putInt(
                    "busType",
                    busType
                )

//                RouterHelper.navigation(RouterHub.ROUTER_HOME_APK_JUMP)
                RouterHelper.navigationPostcard(RouterHub.ROUTER_HOME_APK_JUMP)
                    .withInt("busType", busType)
                    .navigation(requireActivity(), object : NavCallback() {
                        override fun onArrival(postcard: Postcard?) {
                        }

                        override fun onLost(postcard: Postcard?) {
                            ToastUtils.showToast(R.string.common_not_page_ac_hint)
                        }
                    })
            } else {
//                startActivity(ComingSoonActivity.class);
                toAcByAction(classUrl)
            }
        }
    }

    open fun toAcByAction(acName: String?) {
        if (TextUtils.isEmpty(acName)) {

            RouterHelper.navigation(RouterHub.ROUTER_BE_OPENED_ACTIVITY)
            return
        }
        try {
            // 使用别名名字的action
            val intent = Intent()
//            if (vo != null) {
//                val bundle = Bundle()
//                bundle.putSerializable("platformItem", vo)
//                intent.putExtras(bundle)
//            }
            intent.action = acName
            activity?.startActivity(intent)
        } catch (e: Exception) {
//            PToastUtils.t("抱歉、找不到该页面！");
            RouterHelper.navigation(RouterHub.ROUTER_BE_OPENED_ACTIVITY)
        }
    }


    /**
     * 自定义dialog之两个按钮
     *
     * @param title   标题
     * @param message 内容
     */
    open fun showCerAurDialog(left: String?, right: String?, title: String?, message: String?) {
        // 此处this改为getParent()，是因为，第一次安装apk，第一次打开会弹出该dialog提示升级信息，
        // 而集成支付SDK时，先会调到MMPay页面，弹升级dialog时的this即该IndexActivity会找不到，报错
        val dialogBuilder: CustomDialog.Builder = CustomDialog.Builder(requireActivity())

        // 设置标题文字
        dialogBuilder.setTitle(title)

        // 设置提示栏文
        dialogBuilder.setMessage(message)
        dialogBuilder.setConstraint(true)

        // 左键点击事件
        dialogBuilder.setPositiveButton(
            left
        ) { dialog, which ->
            /**
             * [简要描述]:左键点击事件<br></br>
             * [详细描述]:当用户点击左键时触发的事件<br></br>
             * @param dialog 对话框
             * @param which 按钮标识
             * @see android.content.DialogInterface.OnClickListener.onClick
             */
            dialog.dismiss()
        }

        // 右键点击事件
        dialogBuilder.setNegativeButton(
            right
        ) { dialog, which ->
            /**
             * [简要描述]:右键点击事件<br></br>
             * [详细描述]:当用户点击右键时触发的事件<br></br>
             * @param dialog 提示
             * @param which 类型
             * @see android.content.DialogInterface.OnClickListener.onClick
             */
            dialog.dismiss()

            RouterHelper.navigationPostcard(RouterHub.ROUTER_PERSONAL_CER_ACTIVITY)
                .navigation()
        }



        if (mCerAurDialog == null) {
            mCerAurDialog = dialogBuilder.create()
        }

        if (mCerAurDialog?.isShowing == true) return

        mCerAurDialog?.show()
    }


    fun adSignDataList(mTemp: MutableMap<String, String>? = null): MutableList<String> {
        val dataList: MutableList<String> = mutableListOf()

        val exitTime = System.currentTimeMillis()
        val params = mutableMapOf(
            "timestamp" to exitTime.toString(),
        )
        if (mTemp != null) {
            params.putAll(mTemp)
        }

        val stringA = "${
            params.toSortedMap(compareBy { it })
                .entries.joinToString("&") { "${it.key}=${it.value}" }
        }&accessSecret=e9626eed360d405781c38bf115864c8a"

        dataList.add(exitTime.toString())
        dataList.add(Base64Utils.encode(MD5Utils.md5(stringA, false).toByteArray()))
        return dataList
    }
}